package effect
{
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.events.*;
	
	import kim.math.ui.Ball;
	
	[SWF(backgroundColor="#000000")]
	/**
	 * 粒子效果 
	 * @author KimWang
	 * 
	 */
	public class Particle extends MovieClip
	{
		private var contain:MovieClip=new MovieClip();//容器管理粒子
		public function Particle()
		{
			init();
		}
		private function init():void
		{
			addChild(contain);
			stage.addEventListener(MouseEvent.MOUSE_DOWN,MouseDownHandler);
		}
		//生成粒子，200个小球，然后向不同的方向移动，速度不一样，角度也不样
		private function MouseDownHandler(event:MouseEvent):void
		{
			for (var i:int=0; i<200; i++)
			{
				var ball:Ball=new Ball();
				contain.addChild(ball);
				ball.x=mouseX;
				ball.y=mouseY;
				ball.vx=Math.random()*4+2;//随机生成不同的x速度
				ball.vy=Math.random()*5+2;//随机生成不同的y速度
				var angle:Number=Math.atan2(Math.random()*400-ball.y,Math.random()*550-ball.x);//随机一个角度
				ball.angle=angle;
				ball.addEventListener(Event.ENTER_FRAME,BallMove);
			}
		}
		//每一个粒子的移动
		private function BallMove(event:Event):void
		{
			event.currentTarget.x+=Math.cos(event.currentTarget.angle)*event.currentTarget.vx;
			event.currentTarget.y+=Math.sin(event.currentTarget.angle)*event.currentTarget.vy;
			if (event.currentTarget.y<0 || event.currentTarget.y>stage.stageHeight||
				event.currentTarget.x<0 || event.currentTarget.x>stage.stageWidth
			)
			{
				event.currentTarget.removeEventListener(Event.ENTER_FRAME,BallMove);
				contain.removeChild(DisplayObject(event.currentTarget));
			}
		}
		//绘制线条，这个方法你可以尝试一下，
		private function drawLine(x1:Number,y1:Number,x2:Number,y2:Number):void
		{
			graphics.clear();
			graphics.lineStyle(1,0xff0000);
			
			for (var i:int=0; i<=contain.numChildren; i++)
			{
				graphics.moveTo(x1,y1);
				graphics.lineTo(contain.getChildAt(i).x,contain.getChildAt(i).y);
			}
		}
	}
}